//
//  GlobalUtil.m
//  Wanna
//
//  Created by apple on 15/4/10.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "GlobalUtil.h"
#import "MBProgressHUD.h"



@implementation GlobalUtil

+ (MBProgressHUD*)HUDShowMessage:(NSString*)msg addedToView:(UIView*)view
{
   MBProgressHUD* HUD = [[MBProgressHUD alloc] initWithView:view];
    [view addSubview:HUD];
    HUD.labelText = msg;
    HUD.mode = MBProgressHUDModeText;
    
    //指定距离中心点的X轴和Y轴的偏移量，如果不指定则在屏幕中间显示
//        HUD.yOffset = SCREEN_HEIGHT/2-50;
        //HUD.xOffset = 100.0f;
    
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [HUD removeFromSuperview];
       
    }];
    return HUD;
}


+ (MBProgressHUD*)HUDShowMessage:(NSString*)msg addedToView:(UIView*)view completionBlock:(void(^)())block
{
    MBProgressHUD* HUD = [[MBProgressHUD alloc] initWithView:view];
    [view addSubview:HUD];
    HUD.labelText = msg;
    HUD.mode = MBProgressHUDModeText;
    
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [HUD removeFromSuperview];
        block();
    }];
    return HUD;
}

+ (MBProgressHUD *)HUDShowLoadingInView:(UIView *)view{
    MBProgressHUD* HUD = [[MBProgressHUD alloc] initWithView:view];
    [view addSubview:HUD];
    HUD.removeFromSuperViewOnHide = YES;
    [HUD show:YES];
    return HUD;
}



+ (UIBarButtonItem*)createBarButtonItemWithTitle:(NSString*)buttonTitle target:(id)target action:(SEL)action
{
    UIBarButtonItem* item = nil;
    item = [[UIBarButtonItem alloc] initWithTitle:buttonTitle
                                            style:UIBarButtonItemStylePlain
                                           target:target
                                           action:action];
    [item setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor darkGrayColor],  NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    return item;
}
+ (UIBarButtonItem*)createBarButtonItemWithImage:(NSString*)imageNa target:(id)target action:(SEL)action tag:(NSInteger)tag{
    UIButton *btn2=[[UIButton alloc] initWithFrame:CGRectMake(0, 5, 30, 30)];
    [btn2 setImage:[UIImage imageNamed:imageNa] forState:UIControlStateNormal];
    [btn2 setImage:[UIImage imageNamed:imageNa] forState:UIControlStateHighlighted];
    [btn2 setTag:tag];
    [btn2 setContentMode:UIViewContentModeCenter];
    [btn2 addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *bar2=[[UIBarButtonItem alloc] initWithCustomView:btn2];
    
    
    return bar2;
}

//邮箱
+ (BOOL) validateEmail:(NSString *)email

{
  
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
      return [emailTest evaluateWithObject:email];

}

//手机号码验证
+ (BOOL) validateMobile:(NSString *)mobile

{
       //手机号以13， 15，18开头，八个 \d 数字字符
    //((^(13|14|15|17|18)[0-9]{9}$)|(^0[1,2]{1}d{1}-?d{8}$)|(^0[3-9] {1}d{2}-?d{7,8}$)|(^0[1,2]{1}d{1}-?d{8}-(d{1,4})$)|(^0[3-9]{1}d{2}-? d{7,8}-(d{1,4})$))
   
//    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSString *phoneRegex = @"^(1)\\d{10}$";
//    NSString *phoneRegex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
   
    return [phoneTest evaluateWithObject:mobile];
 
}

//金额输入验证
+(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //删除按钮正常响应 @""
    if([string isEqualToString:@""]){
        return YES;
    }
    //禁止非法字符输入
    NSString * regStr = @"^([0-9]|\\.)$";;
    NSPredicate *regexPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regStr];
    if (![regexPre evaluateWithObject:string]) {
        return NO;
    }
    
    
    if(textField.text.length==1&&[[textField.text substringToIndex:1] isEqualToString:@"0"]&&![string isEqualToString:@"."]){
        return NO;
    }
    
    return YES;
}

//用户名
+ (BOOL) validateUserName:(NSString *)name

{
    NSString *regi=@"^[\u4E00-\u9FFF]+$";
    NSPredicate *pre=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",regi];
    BOOL a=[pre evaluateWithObject:name];
    if (a==YES) {
        return a;
    }
    NSString *userNameRegex = @"^[A-Za-z]+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
 
}

//密码
+ (BOOL) validatePassword:(NSString *)passWord
{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}

//昵称
+ (BOOL) validateNickname:(NSString *)nickname
{
  
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
  
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}

//只输入 数字
+ (BOOL) validateNumOnly:(NSString *)inputStr digits:(int)digit{
    NSString * regStr = [NSString stringWithFormat:@"^[0-9]{1,%d}$",digit];
    NSPredicate *regexPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regStr];
    return [regexPre evaluateWithObject:inputStr];
}

//只输入 数字或字母
+ (BOOL) validateNumAndStringOnly:(NSString *)inputStr digits:(int)digit{
    NSString * regStr = [NSString stringWithFormat:@"^[a-zA-Z0-9]{1,%d}$",digit];
    NSPredicate *regexPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regStr];
    return [regexPre evaluateWithObject:inputStr];
}

//身份证号
+ (BOOL) validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

//字符串转换
+(NSString *)changeUrlToUTF:(NSString *)nurl{
   NSString *murl=[nurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
      NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);//gbk code-->utf8 code
    NSData*data = [murl dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString*utf8str = [[NSString alloc] initWithData:data encoding:enc];
    return utf8str;
}

//计算文件大小
+(long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//计算文件夹大小
+(float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath])
        return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

+ (UIImage *)scaleImage:(UIImage *)image toNewSize:(CGSize)size{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
    CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"
                                  keysAndValues:kCIInputImageKey, inputImage,
                        @"inputRadius", @(blur), nil];
    
    CIImage *outputImage = filter.outputImage;
    CIContext *context = [CIContext contextWithOptions:nil]; // save it to self.context
    CGImageRef outImage = [context createCGImage:outputImage fromRect:[outputImage extent]];
    UIImage* output = [UIImage imageWithCGImage:outImage];
    CGImageRelease(outImage);
    return output;
}

+ (void)downloadImageWithURLCache:(NSString*)url completed:(SDWebImageCompletionBlock)completedBlock{
    [[SDImageCache sharedImageCache] queryDiskCacheForKey:url done:^(UIImage *image, SDImageCacheType cacheType){
        if (image) {
            completedBlock(image,nil,cacheType,nil);
        }else{
            [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:url] options:SDWebImageRetryFailed progress:nil
                                                          completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                                                              if (image) {
                                                                  [[SDImageCache sharedImageCache] storeImage:image forKey:url];
                                                              }
                                                              completedBlock(image,error,cacheType,imageURL);
                                                          }];
            
        }
    }];
}

+ (NSString*)getMoneyString:(NSInteger)money{
    if (money % 100 == 0) {
        return [NSString stringWithFormat:@"￥%.0f", money / 100.0];
    } else {
        return [NSString stringWithFormat:@"￥%.02f", money / 100.0];
    }
}

+ (void)deepCleanCollection:(id<NSFastEnumeration>)collection{
    id instance = collection;
    if ([instance isKindOfClass:[NSMutableDictionary class]]) {
        NSMutableDictionary* dict = instance;
        [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if ([obj conformsToProtocol:@protocol(NSFastEnumeration)]) {
                [self deepCleanCollection:obj];
            } else {
                if (obj == [NSNull null]) {
                    [dict setValue:@"" forKey:key];
                }
            }
        }];
    } else if ([instance isKindOfClass:[NSMutableArray class]]) {
        NSMutableArray* array = instance;
        [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if ([obj conformsToProtocol:@protocol(NSFastEnumeration)]) {
                [self deepCleanCollection:obj];
            } else {
                if (obj == [NSNull null]) {
                    [array replaceObjectAtIndex:idx withObject:@""];
                }
            }
        }];
    }
}


//图片压缩
+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

//图片压缩
+ (float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    CGRect textRect = [value boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:(NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil];
    
    return textRect.size.height;
}

//修改图片的颜色：
+ (UIImage *)sectionImage:(UIImage*)image withTintColor:(UIColor*)color {
    if(!image){
        return nil;
    }
    CGRect rect = { CGPointZero, image.size };
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, image.scale); {
        [color set];
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(context, 0, rect.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextClipToMask(context, rect, [image CGImage]);
        CGContextFillRect(context, rect);
    }
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tintedImage;
}

//需要用户登录，才能push页面
//+(void)pushPageWithLoginNeed:(UIViewController *)currentVC toViewController:(UIViewController *)toVC{
//    NSString *memeberId=(NSString *)[UserDefaultHandler getUserDetaultString:kMemeberId];
//    if (memeberId && ![self isNilValue:memeberId]) {
//        [currentVC.navigationController pushViewController:toVC animated:YES];
//    }else{
//        UIStoryboard *loginStoryBoard=[UIStoryboard storyboardWithName:@"Login" bundle:nil];
//        UINavigationController *loginNV=[loginStoryBoard instantiateViewControllerWithIdentifier:@"loginNV"];
//        [currentVC presentViewController:loginNV animated:YES completion:nil];
//    }
//}

//需要用户登录，才能执行block
//+(void)checkLoginNeedWithBlock:(void (^)())block{
//    NSString *memeberId=(NSString *)[UserDefaultHandler getUserDetault:kMemeberId];
//    if (memeberId && ![self isNilValue:memeberId]) {
//        block();
//    }else{
//        UIStoryboard *loginStoryBoard=[UIStoryboard storyboardWithName:@"Login" bundle:nil];
//        UINavigationController *loginNV=[loginStoryBoard instantiateViewControllerWithIdentifier:@"loginNV"];
//        [RootViewController presentViewController:loginNV animated:YES completion:nil];
//    }
//}

// 判断是否是空值，空值返回YES，否则返回NO
+ (BOOL)isNilValue:(NSString *)value {
    if (value == nil || value.length <= 0 || [value isEqualToString:@""] || [value isEqualToString:@"(null)"]) {
        return YES;
    } else {
        return NO;
    }
}

+ (void)removeDelaysofContentTouches:(UITableView*)tableview {
    
    //begin: iOS7 8 中 tabelviewcell中的button 点击效果延迟的解决
    tableview.delaysContentTouches = NO;
    for (id view in tableview.subviews)
    {
        // looking for a UITableViewWrapperView
        if ([NSStringFromClass([view class]) isEqualToString:@"UITableViewWrapperView"])
        {
            // this test is necessary for safety and because a "UITableViewWrapperView" is NOT a UIScrollView in iOS7
            if([view isKindOfClass:[UIScrollView class]])
            {
                // turn OFF delaysContentTouches in the hidden subview
                UIScrollView *scroll = (UIScrollView *) view;
                scroll.delaysContentTouches = NO;
            }
            break;
        }
    }
    //end: iOS7 8 中 tabelviewcell中的button 点击效果延迟的解决
}


+ (void)addGroupedStyletoSection:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath withBorderColor:(UIColor*)color{
    
    if ([cell respondsToSelector:@selector(tintColor)]) {
        CGFloat cornerRadius = 5.0f;
        cell.backgroundColor = UIColor.clearColor;
        CAShapeLayer *layer = [[CAShapeLayer alloc] init];
        CGMutablePathRef pathRef = CGPathCreateMutable();
        CGRect bounds = CGRectInset(cell.bounds, 0, 0);
        BOOL addLine = NO;
        if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
            CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
        }
        else if (indexPath.row == 0) {
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
            addLine = YES;
        }
        else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
            CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
            CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
            CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
        }
        else {
            CGPathAddRect(pathRef, nil, bounds);
            addLine = YES;
        }
        layer.path = pathRef;
        CFRelease(pathRef);
        //set the border color
        layer.strokeColor = color.CGColor; //[UIColor lightGrayColor].CGColor;
        //set the border width
        layer.lineWidth = 0.5f;
        layer.fillColor = [UIColor colorWithWhite:1.f alpha:1.0f].CGColor;
        
        
        if (addLine == YES) {
            CALayer *lineLayer = [[CALayer alloc] init];
            CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
            lineLayer.frame = CGRectMake(CGRectGetMinX(bounds), bounds.size.height-lineHeight, bounds.size.width, lineHeight);
            lineLayer.backgroundColor = tableView.separatorColor.CGColor;
            [layer addSublayer:lineLayer];
        }
        
        UIView *testView = [[UIView alloc] initWithFrame:bounds];
        [testView.layer insertSublayer:layer atIndex:0];
        testView.backgroundColor = UIColor.clearColor;
        cell.backgroundView = testView;
    }
    
}

// 修改图片size
+ (UIImage *)image:(UIImage*)image byScalingToSize:(CGSize)targetSize {
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    
    UIGraphicsBeginImageContext(targetSize);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = CGPointZero;
    thumbnailRect.size.width  = targetSize.width;
    thumbnailRect.size.height = targetSize.height;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage ;
}



+(NSString *)setUpTime:(NSString *)time{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    double lastactivityInterval = [time doubleValue];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:lastactivityInterval];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}


//present登录页面
+ (void)presentLoginVC {
    STMLoginViewController *loginVC = [[STMLoginViewController alloc] init];
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    loginVC.loginVCBlock = ^{
        [nav popViewControllerAnimated:NO];
    };
    [nav presentViewController:loginVC animated:YES completion:nil];
}


//根据内容计算label高度
+ (CGFloat)getLabelHeightWithContent:(NSString *)content
                         fontSize:(CGFloat)size
                       labelWidth:(CGFloat)width {
    UILabel *tmpLabel = [[UILabel alloc] init];
    tmpLabel.font = [UIFont systemFontOfSize:size];
    tmpLabel.numberOfLines = 0;
    tmpLabel.lineBreakMode = NSLineBreakByCharWrapping;
    tmpLabel.text = content;
    CGSize maximumLabelSize = CGSizeMake(width, 1000);
    CGSize expectContentLabelSize = [tmpLabel sizeThatFits:maximumLabelSize];
    return expectContentLabelSize.height;
}


@end
